using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters; 
using QQZiFramework;
using QQZiFramework.Mvc;

namespace QQZiCore.Mvc
{
    [System.AttributeUsage(System.AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AccessLogAttribute : ActionFilterAttribute
    {
        public const string DBCONTEXT_NAME_IN_HTTP_CONTEXT = "qqzi-context";

        public AccessLogAttribute()
        {
            base.Order = 100;//放最后
        }
        /// <summary>
        /// 不要记录提交到Action的信息（客户端提交上来的参数等）
        /// </summary>
        public bool DoNotLogRequest { get; set; }

        /// <summary>
        /// 执行模块名称，Action的中文名，用来记录日志
        /// </summary>
        public string Alias { get; set; }

        //是否需要忽略控制器的Filter（Action上有定义过滤器的，这里不执行控制器的过滤器）
        protected virtual bool IgonreControllerFilter(FilterContext filterContext)
        {
            return false;
        }

        public override async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            DBContext context;
            if (filterContext.HttpContext.Items.ContainsKey(DBCONTEXT_NAME_IN_HTTP_CONTEXT))
            {
                context = (DBContext)filterContext.HttpContext.Items[DBCONTEXT_NAME_IN_HTTP_CONTEXT];
            }
            else
            {
                context = ((QQZiFramework.Mvc.IQQZiController)filterContext.Controller).CreateDBContext();
            }
            OEMMemberShip webMemberShip = (OEMMemberShip)context.Membership;
            var start= DateTime.Now;
            if (!DoNotLogRequest)
            {
                //requestContent
                // webMemberShip.LogBeforeAction(context, filterContext, Alias);
            }
            await next();             
            var action = context.GetArgument<string>("__ACTION_NAME");
            string url = WebHostMemberShip.GetPathAndQuery(filterContext.HttpContext.Request);
            context.LogDebug("finish in " + (DateTime.Now - start).TotalMilliseconds.ToString() + "ms", url);
        }

    }



    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public class DefaultAccessLogAttribute : AccessLogAttribute
    {
        
        protected override bool IgonreControllerFilter(FilterContext filterContext)
        {
            //如果有方法有AccessLog过滤器，则Default过滤器不执行
            if (filterContext.Filters.FirstOrDefault((x) => x.GetType() == typeof(AccessLogAttribute)) != null) return true;
            return false;
        }

        public override async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            if (IgonreControllerFilter(filterContext))
            {
                await next();
            }
            else
            {
                await base.OnActionExecutionAsync(filterContext, next);
            }
        }


    }
}